package com.senseauto.mediacodecdemo;

import android.Manifest;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureFailure;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.util.Size;
import android.view.Surface;
import android.view.TextureView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;

/**
 * 平板上camera2打开预览摄像头，然后编码数据写入文件, 权限在前一个界面已经申请好了
 * 用Camera2的api是因为车机上不支持Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK)操作
 * 车机上 1920*1080的图像编码底部有绿条，MediaCodec格式选的MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar
 */
public class Camera2Activity extends AppCompatActivity implements EncoderListener {
    private String TAG = "Camera2Activity";
    private AutoFitTextureView mTextureView;
    private int cameraId = 0;//车机台架摄像头id=47 平板摄像头id=0

    private Size mPreviewSize;
    private CameraManager cameraManager;
    private HandlerThread mCameraThread;
    private Handler cameraHandler;

    private CameraDevice cameraDevice;
    private SurfaceTexture surfaceTexture;
    private CameraCaptureSession captureSession;
    private ImageReader imageReader;
    private long encodeTime;

    private YuvEncoderH264 yuvEncoderH264;
    //private YuvEncoderH264Thread yuvEncoderH264Thread;
    private boolean hasShowOne = false;
    private String videoSavePath;
    private FileOutputStream fos;

    //主线程的handler
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera2);
        videoSavePath = createFile();
        int carType = Constants.getCurrentCarType();
        Log.e(TAG, "carType=" + carType);
        /*if (carType == 1) { //AH8的车
            cameraId = 47;
        } else {
            cameraId = 0;
        }*/
        try {
            initView();
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() throws CameraAccessException {
        initHandler();
        mTextureView = findViewById(R.id.texture);
        cameraManager = getSystemService(CameraManager.class);
        findViewById(R.id.btnRecord).setOnClickListener(v->{
            yuvEncoderH264.recodingChange();
            if(yuvEncoderH264.getRecodingStatus()){//正在录制视频

            }else{ //停止录制视频了，需要重新初始化保存的文件路径
                Log.e(TAG, "停止录制视频了，需要重新初始化保存的文件路径");
            }
        });
        mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
                try {
                    surfaceTexture = surface;
                    initCameraInfo();
                    openCamera();
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {

            }

            @Override
            public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {

            }
        });
    }

    private void initCameraInfo() throws CameraAccessException {
        CameraCharacteristics cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId + "");
        StreamConfigurationMap map = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        Size[] sizes = map.getOutputSizes(SurfaceTexture.class);
        Log.e(TAG, "outputSizes->" + (sizes != null ? sizes.length : -1));
        //下面这里稍微做了修改，原来的代码是直接获取第0个原始，这里改成了返回16：9的尺寸并且最小的要大于1000
        Size photoSize = null;
        photoSize = getBestSize(sizes);
        if (photoSize != null) {
            mPreviewSize = photoSize;
        } else {
            photoSize = new Size(1920, 1080);
        }
        mTextureView.getSurfaceTexture().setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        Log.e(TAG, "预览属性的宽高：" + mPreviewSize.getWidth() + " " + mPreviewSize.getHeight());

        //TextureView预览画面有90度旋转的问题(平板上需要选择90度来预览，车机上不需要)
        configureTransform(photoSize.getWidth(), photoSize.getHeight());

        yuvEncoderH264 = new YuvEncoderH264(this, photoSize.getWidth(), photoSize.getHeight());
        //yuvEncoderH264.setVideoSavePath(videoSavePath);
        yuvEncoderH264.setEncoderListener(this);

        imageReader = ImageReader.newInstance(photoSize.getWidth(), photoSize.getHeight(), ImageFormat.YUV_420_888, 2);
        imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(ImageReader reader) {
                Image image = reader.acquireLatestImage();
                if (image != null) {
                    if (encodeTime == 0) {
                        encodeTime = System.currentTimeMillis();
                    }
                    Image.Plane[] planes = image.getPlanes();
                    if(!hasShowOne){
                        hasShowOne = true;
                        for (int i = 0; i < planes.length; i++) {
                            ByteBuffer iBuffer = planes[i].getBuffer();
                            Log.i(TAG, "pixelStride  " + planes[i].getPixelStride());
                            Log.i(TAG, "rowStride   " + planes[i].getRowStride());
                            Log.i(TAG, "width  " + image.getWidth());
                            Log.i(TAG, "height  " + image.getHeight());
                            Log.i(TAG, "Finished reading data from plane  " + i);
                        }
                    }

                    byte[] imageYUV = null;
                    if (planes.length >= 3) {
                        //android 默认出图的是NV21的数据 yyyyvuvu
                        ByteBuffer bufferY = image.getPlanes()[0].getBuffer();
                        byte[] dataY = new byte[bufferY.remaining()];
                        bufferY.get(dataY);
                        /**
                         * plane[1] : UVUVUVUVUVUVUVUV…
                         * plane[2] : VUVUVUVUVUVUVUVU…
                         *
                         *
                         * plane[0] + plane[1] 可得NV12
                         * plane[0] + plane[2] 可得NV21
                         */
                        //平板上，需要取plane[0]和plane[1]的数据组成nv12拿去编码视频才不会变色，plane[0]和plane[2]组成的nv21的数据去编码会变色
                        ByteBuffer bufferUV = image.getPlanes()[1].getBuffer();
                        byte[] dataUV = new byte[bufferUV.remaining()];
                        bufferUV.get(dataUV);
                        if(yuvEncoderH264.getRecodingStatus()){
                            byte[]mImageData = new byte[image.getWidth()* image.getHeight() * 3 / 2];
                            System.arraycopy(dataY, 0, mImageData, 0, dataY.length);
                            System.arraycopy(dataUV, 0, mImageData, image.getWidth()* image.getHeight(), dataUV.length);
                            //手机和平板上能马上编码成功并释放队列里的 编码芯片
                            yuvEncoderH264.encoderH264(mImageData);
                            //每5s取一帧数据拿去编码视频
                            //encodeTime = System.currentTimeMillis();
                        }
                        //每5s取一帧数据拿去编码视频
                        //encodeTime = System.currentTimeMillis();

                    }
                    image.close();
                }
            }
        }, cameraHandler);
    }

    //旋转屏幕画面
    private void configureTransform(int viewWidth, int viewHeight) {

        if (null == mTextureView || mPreviewSize == null) {
            return;
        }
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        Matrix matrix = new Matrix();
        RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
        RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
        float centerX = viewRect.centerX();
        float centerY = viewRect.centerY();
        if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
            bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
            matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
            float scale = Math.max(
                    (float) viewHeight / mPreviewSize.getHeight(),
                    (float) viewWidth / mPreviewSize.getWidth());
            matrix.postScale(scale, scale, centerX, centerY);
            matrix.postRotate(90 * (rotation - 2), centerX, centerY);
        } else if (Surface.ROTATION_180 == rotation) {
            matrix.postRotate(180, centerX, centerY);
        }
        mTextureView.setTransform(matrix);
    }

    /**
     * 打开相机
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void openCamera() throws CameraAccessException {

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            Log.e(TAG, "没有摄像头权限");
            return;
        }
        cameraManager.openCamera(cameraId + "", new CameraDevice.StateCallback() {
            @Override
            public void onOpened(@NonNull CameraDevice camera) {
                cameraDevice = camera;
                createCaptureSession(camera);
                //yuvEncoderH264.startRecord();//打开摄像头之后再开始录制视频(也可以手动点按钮开始录制)
            }

            @Override
            public void onDisconnected(@NonNull CameraDevice camera) {

            }

            @Override
            public void onError(@NonNull CameraDevice camera, int error) {

            }
        }, cameraHandler);
    }

    public void initHandler() {
        mCameraThread = new HandlerThread("CameraThread");
        mCameraThread.start();
        cameraHandler = new Handler(mCameraThread.getLooper());
    }

    private CameraCaptureSession.CaptureCallback mCaptureCallBack = new CameraCaptureSession.CaptureCallback() {
        @Override
        public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
            super.onCaptureCompleted(session, request, result);
        }

        @Override
        public void onCaptureFailed(CameraCaptureSession session, CaptureRequest request, CaptureFailure failure) {
            super.onCaptureFailed(session, request, failure);
            Log.e(TAG, "onCaptureFailed");
        }

        @Override
        public void onCaptureStarted(CameraCaptureSession session, CaptureRequest request, long timestamp, long frameNumber) {
            super.onCaptureStarted(session, request, timestamp, frameNumber);
        }
    };

    private void createCaptureSession(CameraDevice cameraDevice) {
        try {
            CaptureRequest.Builder builder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            Surface surface = new Surface(surfaceTexture);
            builder.addTarget(surface);
            builder.addTarget(imageReader.getSurface());
            builder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); // 自动对焦
            builder.set(CaptureRequest.JPEG_ORIENTATION, 0);//横屏可以不用旋转，竖屏需要顺时针旋转90度
            cameraDevice.createCaptureSession(Arrays.asList(surface, imageReader.getSurface()), new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(@NonNull CameraCaptureSession session) {
                    Log.e(TAG, "Session创建好了");
                    captureSession = session;
                    try {
                        captureSession.setRepeatingRequest(builder.build(), mCaptureCallBack, mHandler);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession session) {

                }
            }, cameraHandler);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取设备支持的最大分辨率
     */
    private Camera.Size getCameraPreviewSize(Camera.Parameters parameters) {
        List<Camera.Size> list = parameters.getSupportedPreviewSizes();
        Camera.Size needSize = null;
        for (Camera.Size size : list) {
            if (needSize == null) {
                needSize = size;
                continue;
            }
            if (size.width >= needSize.width) {
                if (size.height > needSize.height) {
                    needSize = size;
                }
            }
        }
        return needSize;
    }

    //放回文件保存地址
    private String createFile() {
        //这个文件用来保存编码后的视频，用VLC media Player可以打开这个文件
        File file = new File(getExternalCacheDir(), "VideoH264.h264");
        Log.e(TAG, "视频保存：" + file.getAbsolutePath());
        try {
            fos = new FileOutputStream(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }

    //获取最佳预览尺寸,宽度在1000到2000之间，16:9的宽高比的尺寸
    private Size getBestSize(Size[] outputSizes) {
        Size photoSize = null;
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            boolean flag = false;
            for (int i = 0; i < outputSizes.length; i++) {
                if (outputSizes[i].getHeight() * 1.0 / outputSizes[i].getWidth() == 9.0 / 16
                        && outputSizes[i].getWidth() <= 2000 && outputSizes[i].getHeight() >= 1000) {
                    photoSize = outputSizes[i];
                    flag = true;
                    break;
                }
            }
            /*for (int i = 0; i < outputSizes.length; i++) {
                if (outputSizes[i].getHeight() * 1.0 / outputSizes[i].getWidth() == 9.0 / 16
                        && outputSizes[i].getWidth() <= 1500 && outputSizes[i].getHeight() >= 500) {
                    photoSize = outputSizes[i];
                    flag = true;
                    break;
                }
            }*/
            if (!flag) {
                photoSize = outputSizes[0];
            }
        } else {
            //输出尺寸发现，  （宽度大于或者等于高度），结果取到的第0个就是 正方形的（宽高相同的）
            Log.e(TAG, "竖屏找对应的合适的尺寸");
            boolean flag = false;
            for (int i = 0; i < outputSizes.length; i++) {
                //这里发现个问题，虽然按16：9的尺寸来找合适的图片大小比例，但是如果图片尺寸宽高太大了或者太小了，底层可能会识别不到人脸，所以后面加了宽高的限制条件
                if ((outputSizes[i].getWidth() * 1.0 / outputSizes[i].getHeight()) == (9.0 / 16)
                        && outputSizes[i].getHeight() <= 2000 && outputSizes[i].getWidth() >= 1000) {
                    photoSize = outputSizes[i];
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                Log.e(TAG, "横屏找对应的合适的尺寸====>只取到第0个");
                photoSize = outputSizes[0];
            }
        }
        return photoSize;
    }

    @Override
    public void onStop() {
        super.onStop();
        /*if(yuvEncoderH264!=null){
            yuvEncoderH264.stopRecord();
        }*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseCamera();
    }

    public void releaseCamera() {
        if (captureSession != null) {
            captureSession.close();
            captureSession = null;
        }

        cameraDevice.close();
        cameraDevice = null;

        if (imageReader != null) {
            imageReader.close();
            imageReader = null;
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            fos = null;
        }
        releaseThread();
    }

    public void releaseThread() {
        mCameraThread.quitSafely();
    }

    @Override
    public void h264(byte[] data) {
        try {
            //编码后的视频数据写入磁盘文件
            fos.write(data);
            //Log.e(TAG, "写编码后的数据到文件");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}